// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "sparrow/base64.h"

#include <stddef.h>

#include "src/base64/modp_b64.h"

extern "C" {
void Base64Encode(const void *input, int input_size, struct FlexibleArray **output) {
    struct FlexibleArray *temp =
        FlexibleArrayInit(modp_b64_encode_len(input_size)); // makes room for null byte

    // modp_b64_encode_len() returns at least 1, so output[0] is safe to use.
    const size_t output_size =
        modp_b64_encode(&temp->data[0], reinterpret_cast<const char *>(input), input_size);

    temp->length = output_size;
    *output = temp;
}

int Base64Decode(const void *input, int input_size, struct FlexibleArray **output) {
    struct FlexibleArray *temp = FlexibleArrayInit(modp_b64_decode_len(input_size));

    // does not null terminate result since result is binary data!
    size_t output_size =
        modp_b64_decode(&temp->data[0], static_cast<const char *>(input), input_size);
    if (output_size == MODP_B64_ERROR) {
        *output = NULL;
        return -1;
    }
    temp->length = output_size;
    *output = temp;
    return 0;
}
} // extern "C"
